package com.ujiuye.controller;

import com.ujiuye.pojo.Employee;
import com.ujiuye.service.EmployeeService;
import com.ujiuye.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/auth")
public class AuthContoller {
    @Autowired
    private EmployeeService employeeService;

    //登录
    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session, boolean autoLogin, HttpServletResponse response){
        Employee employee = employeeService.login(username, password);
        if (employee==null){//登录成功
            return "fail";
        }
        if (autoLogin==true){//记住密码
            password = MD5Utils.stringToMD5("adsad"+password+"12345");
            Cookie cookie = new Cookie("auth",username+"=="+password);
            cookie.setMaxAge(60*60*24*7);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        session.setAttribute("LOGIN_SESSION",employee);
        return "success";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session,HttpServletResponse response){
        //干掉session
        session.setAttribute("LOGIN_SESSION",null);
        //干掉cookie
        Cookie cookie = new Cookie("auth","");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "success";
    }
}
